import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import {
  removeSelectComponent,
  changeComponentHidden,
  toggleChangeLock,
  copySelectComponent,
  pasteSelectComponent,
  selectPreComponent,
  selectNextComponent,
} from "../store/componentReducer/index";

//判断activeElem是否合法
function isActiveElementValid() {
  const activeElem = document.activeElement;
  if (activeElem === document.body) return true; //光标没有在input
  return false;
}

function useBindCanvasKeyPress() {
  const dispatch = useDispatch();
  //删除
  useKeyPress(["backspace", "delete"], () => {
    if (!isActiveElementValid()) return;

    dispatch(removeSelectComponent());
  });
  //复制
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid()) return;
    dispatch(copySelectComponent());
  });
  //粘贴
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementValid()) return;
    dispatch(pasteSelectComponent());
  });
  //选中上一个
  useKeyPress("uparrow", () => {
    if (!isActiveElementValid()) return;
    dispatch(selectPreComponent());
  });

  //选中下一个
  useKeyPress("downarrow", () => {
    if (!isActiveElementValid()) return;
    dispatch(selectNextComponent());
  });
}
export default useBindCanvasKeyPress;
